<?php

namespace App\Http\Controllers\Admin;

use App\Helpers\Logger\SLogger;
use App\Models\Factory\UsersFactory;
use App\Models\Orm\AwAuditRecord;
use App\Models\Orm\CooperativeCompany;
use App\Models\Orm\Product;
use App\Models\Orm\ProductAudit;
use App\Models\Orm\ProductLabels;
use App\Models\Orm\ProjectProduct;
use App\Models\Orm\Recommend;
use App\Models\Orm\SecondsKill;
use App\Models\Orm\Users;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Maatwebsite\Excel\Facades\Excel;


/**
 * 产品模块控制器
 *
 * Class ProductController
 * @package App\Http\Controllers\Admin
 */
class UsersController extends Controller
{



    // 列表页表头
    private $list_excel_header = [
        '手机号',
        '姓名',
        '注册时间',
    ];




    /**
     * 产品列表(展示页)
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {

        $data = Users::whereNotNull('name')->orderby('id', SORT_DESC)->paginate(50,  ['*'],  'spage');;

        return view('admin.users.index', compact('data'));

    }


    /**
     * 数据导出Excel通用方法
     *
     * @param Request $request
     */
    public function excel(Request $request)
    {

        set_time_limit(0);
        $time = $request->input('time');
        if($time && !empty($time))
        {
            $time = explode('-',$time);
            $start_time  = $time[0];
            $end_time    = $time[1];
            if(date('Y-m-d',strtotime($start_time)) == date('Y-m-d',strtotime($end_time)))
            {
                $date = date('Y-m-d',strtotime($start_time));
                $start_time = $date.' 00:00:00';
                $end_time = $date.' 24:00:00';
            }

        }else{
            $start_time = $end_time = '';

        }



                $header = $this->list_excel_header;
                $data = UsersFactory::getUser($start_time,$end_time);
                $file_name = '前台用户表' . date('Y-m-d');

                // 组装数据
                $return_data = [$header];

                foreach ($data as $item) {
                    $return_data[] = [
                        $item ->userphone,
                        $item->name,
                        $item ->registe_time,

                    ];
                }


        // 导出表格
        Excel::create($file_name, function ($excel) use ($return_data) {
            $excel->sheet('score', function ($sheet) use ($return_data) {
                $sheet->rows($return_data);
            });
        })->export('xls');

    }



    public function create(Request $request)
    {



        if ($request->isMethod('post')) {
            set_time_limit(0);
            $request->flash();
            $insert_data = $request ->all();
            $realPath = $insert_data['img_pc']->getRealPath();

            DB::beginTransaction();
            try {

                $content = trim(file_get_contents($realPath));
                $excelData = explode("\n",$content);

                $chunkData = array_chunk($excelData , 5000); // 将这个10W+ 的数组分割成5000一个的小数组。这样就一次批量插入5000条数据。mysql 是支持的。
                $count = count($chunkData);
                for ($i = 0; $i < $count; $i++) {
                    foreach($chunkData[$i] as $value){
                        $string = mb_convert_encoding(trim(strip_tags($value)), 'utf-8', 'gbk');//转码
                        $v = explode(',', trim($string));
                        if(isset($v[0])&&isset($v[1])){
                            if($v[0] && preg_match("/^1[34578]\d{9}$/", $v[1])) {
                                $excel['name'] = $v[0];//转化编码
                                $excel['userphone'] = $v[1];
                                $excel['terminal'] = 4;
                                $rdate = mt_rand(time() - 3600 * 24 * 3, time());
                                $excel['registe_time'] = date("Y-m-d h:i:s", $rdate);
                                Users::updateOrCreate(['userphone' => $v[1]], $excel);
                            }else{
                                    continue;
                                }

                    }else{
                        continue;
                        }

                    }
                }



                SLogger::getStream()->info('事务成功');
                DB::commit();


            } catch (\Exception $e) {
                DB::rollBack();
                SLogger::getStream()->info('异常');
                SLogger::getStream()->info($e);

            }
            // 用户ID

//            dd($insert_data);
            return redirect('/admin/qian/index')->with(['success' => '您的申请已提交,请耐心等等待审核']);
        }


        return view('admin.users.create');
    }



    /**
     * 筛选
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function search(Request $request)
    {
        $data = $request->input();

        $userphone = isset($data['userphone']) ? $data['userphone'] : '';
        $time      = isset($data['time']) ? $data['time'] : '';
        $query = users::select('id','userphone','name','registe_time');




        if ($userphone && !empty($userphone))
        {
            $query = $query->where('user.userphone','like','%'.$userphone.'%');
        }

        if($time && !empty($time))
        {
            $time = explode('-',$time);
            $start_time  = $time[0];
            $end_time    = $time[1];
            if(date('Y-m-d',strtotime($start_time)) == date('Y-m-d',strtotime($end_time)))
            {
                $date = date('Y-m-d',strtotime($start_time));
                $start_time = $date.' 00:00:00';
                $end_time = $date.' 24:00:00';
            }
            $query = $query->where('user.registe_time','>=',$start_time)->where('user.registe_time','<=',$end_time);
        }

        $data = $query->paginate(50,  ['*'],  'spage');



        return view('admin.users.index', compact('data'));
    }

}